#include "setmemberlevel.h"
#include "ui_setmemberlevel.h"
#include "inquiresql.h"
#include <QMessageBox>
#include "personmember.h"
#include <QKeyEvent>

SetMemberLevel::SetMemberLevel(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SetMemberLevel)
{
    ui->setupUi(this);
    this->setLayout(ui->MainLayout);
    this->setFixedSize(286,351);
    setWindowTitle(tr("会员等级设置"));
    m_lastClick = -1;

    //设置自定义的鼠标指针图案
    QCursor *myCursor= new QCursor(QPixmap(":/Mouse/Image/mouse/mouse.png"),15,10);
    setCursor(*myCursor);

    //正则表达式语句中不能乱加空格
    QRegExp regExpDiscount("[0-9]{1,2}|100");
    QRegExpValidator *pRegExpValidatorDiscount = new QRegExpValidator(regExpDiscount, this);
    ui->lineEditMemberDiscount->setValidator(pRegExpValidatorDiscount);

    QRegExp regExpPrice(" [0-9]{0,6}|[0-9]{0,6}[.]{1}[0-9]{0,2} ");
    QRegExpValidator *pRegExpValidatorPrice = new QRegExpValidator(regExpPrice, this);
    ui->lineEditInitAmount->setValidator(pRegExpValidatorPrice);

    QRegExp regExpIntegration("[0-9]{1,5}");
    QRegExpValidator *pRegExpValidatorIntegration = new QRegExpValidator(regExpIntegration, this);
    ui->lineEditInitIntegration->setValidator(pRegExpValidatorIntegration);

    QHeaderView* vheaderView = ui->tableWidgetMemberLevel->verticalHeader();
    vheaderView->setHidden(true);

    //添加时间过滤器
    ui->lineEditMemberLevel->installEventFilter(this);
    ui->lineEditMemberDiscount->installEventFilter(this);
    ui->lineEditInitAmount->installEventFilter(this);
    ui->lineEditInitIntegration->installEventFilter(this);
}

SetMemberLevel::~SetMemberLevel()
{
    delete ui;
}

void SetMemberLevel::displayMemberLevel()
{
    m_currentTableWidgetList.clear();
    m_currentTableWidgetList = m_sql->InquireMemberLevel();

    //显示会员等级信息
//    ui->tableWidgetMemberLevel->clear();
    ui->tableWidgetMemberLevel->setRowCount(m_currentTableWidgetList.count());

    setTableWidgetHeaderStyle();

    for(int i = 0; i < m_currentTableWidgetList.count(); ++i)
    {
        QTableWidgetItem *memberLevel      = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_memberLevel());
        QTableWidgetItem *discount         = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_discount());
        QTableWidgetItem *membercardAmount = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_membercardAmount());
        QTableWidgetItem *integration      = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_integration());

        //设置商品编号,单价 数量 合计 为居中对齐
        memberLevel->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        discount->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        membercardAmount->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        integration->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
//        memberLevel->setFont(QFont("Helvetica")); //设置字体
//        memberLevel->setBackgroundColor(QColor(0,60,10)); //设置单元格背景颜色
//        memberLevel->setTextColor(QColor(255,0,255)); //设置文字颜色

        ui->tableWidgetMemberLevel->setItem(i, 0, memberLevel);
        ui->tableWidgetMemberLevel->setItem(i, 1, discount);
        ui->tableWidgetMemberLevel->setItem(i, 2, membercardAmount);
        ui->tableWidgetMemberLevel->setItem(i, 3, integration);
    }

    ui->tableWidgetMemberLevel->setCurrentItem(
                ui->tableWidgetMemberLevel->item(m_currentTableWidgetList.count() - 1, 0));

    //设置与文字相匹配的单元格大小
    ui->tableWidgetMemberLevel->resizeColumnsToContents();
    ui->tableWidgetMemberLevel->resizeRowsToContents();

    displayMemberLevelInformation(m_currentTableWidgetList.at(m_currentTableWidgetList.count() - 1));

    setTableWidgetColor();
}

bool SetMemberLevel::eventFilter(QObject *target, QEvent *event)
{
    if ( target == ui->lineEditMemberLevel || target == ui->lineEditMemberDiscount
      || target == ui->lineEditInitAmount || target == ui->lineEditInitIntegration )
    {
        //鼠标左键按下事件
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                if (target == ui->lineEditMemberLevel)
                {
                    if (m_lastClick != lineEditMemberLevel) {
                        ui->lineEditMemberLevel->selectAll();
                        m_lastClick = lineEditMemberLevel;
                        return true;
                    }else if (m_lastClick == lineEditMemberLevel)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditMemberDiscount)
                {
                    if (m_lastClick != lineEditMemberDiscount){
                        ui->lineEditMemberDiscount->selectAll();
//                        event->accept();
                        m_lastClick = lineEditMemberDiscount;
                        return true;
                    }else if (m_lastClick == lineEditMemberDiscount)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditInitAmount)
                {
                    if (m_lastClick != lineEditInitAmount){
                        m_lastClick = lineEditInitAmount;
                        ui->lineEditInitAmount->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditInitAmount)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditInitIntegration)
                {
                    if (m_lastClick != lineEditInitIntegration){
                        m_lastClick = lineEditInitIntegration;
                        ui->lineEditInitIntegration->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditInitIntegration)
                    {
                        goto flag;
                    }
                }
            }
        }

        //键盘事件
        if (event->type() == QEvent::KeyPress)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
            if (keyEvent->key() == Qt::Key_Escape)
            {
                this->hide();
                return true;
            }
            if ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))
            {
                if (target == ui->lineEditMemberLevel)
                {
                    ui->lineEditMemberDiscount->setFocus();
                    ui->lineEditMemberDiscount->selectAll();
                    return true;
                }
                if (target == ui->lineEditMemberDiscount)
                {
                    ui->lineEditInitAmount->setFocus();
                    ui->lineEditInitAmount->selectAll();
                    return true;
                }
                if (target == ui->lineEditInitAmount)
                {
                    ui->lineEditInitIntegration->setFocus();
                    ui->lineEditInitIntegration->selectAll();
                    return true;
                }
                if (target == ui->lineEditInitIntegration)
                {
                    ui->lineEditMemberLevel->setFocus();
                    ui->lineEditMemberLevel->selectAll();
                    return true;
                }
            }
        }
    }
flag:
    return QWidget::eventFilter(target, event);
}

void SetMemberLevel::setTableWidgetColor()
{
    for (int i = 0; i < ui->tableWidgetMemberLevel->rowCount(); ++i)
    {
        if (i % 2 == 0)
        {
            for (int j = 0; j < ui->tableWidgetMemberLevel->columnCount(); ++j)
            {
                QTableWidgetItem *item = ui->tableWidgetMemberLevel->item(i,j);
                if (item)
                {
                    const QColor color = QColor(252,222,156);
                    item->setBackgroundColor(color);
                }
            }
        }
    }
}

void SetMemberLevel::setTableWidgetHeaderStyle()
{
    QStringList headers;
    headers << tr("会员等级") << tr("折扣") << tr("初始金额") << tr("初始积分");

    ui->tableWidgetMemberLevel->setColumnCount(4);
    ui->tableWidgetMemberLevel->setHorizontalHeaderLabels(headers);

    for (int i = 0; i < 4; ++i)
    {
        ui->tableWidgetMemberLevel->horizontalHeaderItem(i)->setFont(QFont("Helvetica"));
        ui->tableWidgetMemberLevel->horizontalHeaderItem(i)->setTextColor(QColor(200,111,30));
    }
}

void SetMemberLevel::displayMemberLevelInformation(const PersonMember &memberLevelInformation)
{
    ui->lineEditMemberLevel->setText(memberLevelInformation.get_memberLevel());
    ui->lineEditMemberDiscount->setText(memberLevelInformation.get_discount());
//    ui->lineEditInitAmount->setText(memberLevelInformation.get_membercardAmount());
    ui->lineEditInitAmount->setText(completionPrice(memberLevelInformation.get_membercardAmount()));
    ui->lineEditInitIntegration->setText(memberLevelInformation.get_integration());
}

QString SetMemberLevel::completionPrice(const QString &price)
{
    QString number = price;
    if (number.isEmpty())
    {
        number.append("0.00");
        return number;
    }
    if (number.contains(".", Qt::CaseInsensitive))
    {
        if (number.left(1) == ".")
        {
            number.replace(0, 1, "0.");
            return number;
        }
        if (number.right(1) == ".")
        {
            number.append("00");
            return number;
        }
        if (number.right(2).contains(".", Qt::CaseInsensitive))
        {
            number.append("0");
            return number;
        }
    }
    else
    {
        number.append(".00");
        return number;
    }

    return NULL;
}

void SetMemberLevel::on_pushButtonNew_clicked()
{
    if (ui->lineEditMemberLevel->text().isEmpty())
    {
        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("\n请输入会员等级") );
        ui->lineEditMemberLevel->setFocus();
        return;
    }
    for(int i = 0; i < m_currentTableWidgetList.count(); ++i)
    {
        if (m_currentTableWidgetList.at(i).get_memberLevel() == ui->lineEditMemberLevel->text())
        {
            QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."),
                                 tr("\n此会员等级已存在,不允许重复设置!"));
            return;
        }
    }    
    //插入会员等级 
    int memberLevelNumber = m_currentTableWidgetList.at(m_currentTableWidgetList.count() - 1)
            .get_memberLevelNumber().toInt() + 1;
    PersonMember personMember(QString::number(memberLevelNumber).rightJustified(4, '0'),
                              ui->lineEditMemberLevel->text(), ui->lineEditMemberDiscount->text(),
                              ui->lineEditInitAmount->text(), ui->lineEditInitIntegration->text());
    if (!m_sql->InsertMemberLevel(personMember))
    {
        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."),
                             tr("\n插入会员等级失败!"));
    }
    else
    {
        displayMemberLevel();
        emit updateMemberLevel();
//        ui->tableWidgetMemberLevel->clear();
    }
}


void SetMemberLevel::on_tableWidgetMemberLevel_currentCellChanged(int currentRow, int, int, int)
{
    displayMemberLevelInformation(m_currentTableWidgetList.at(currentRow));
}

void SetMemberLevel::on_pushButtonDelete_clicked()
{
    m_sql->DeleteMemberLevel(
                ui->tableWidgetMemberLevel->item(ui->tableWidgetMemberLevel->currentRow(), 0)->text());
    displayMemberLevel();
    emit updateMemberLevel();
}

void SetMemberLevel::on_pushButtonModify_clicked()
{
    //更新会员等级
    for(int i = 0; i < m_currentTableWidgetList.count(); ++i)
    {
        if ( m_currentTableWidgetList.at(i).get_memberLevel()
             == (ui->tableWidgetMemberLevel->item(ui->tableWidgetMemberLevel->currentRow(), 0)->text()) )
        {
            PersonMember personMember(m_currentTableWidgetList.at(i).get_memberLevelNumber(),
                        ui->lineEditMemberLevel->text(), ui->lineEditMemberDiscount->text(),
                        ui->lineEditInitAmount->text(), ui->lineEditInitIntegration->text());
            if (!m_sql->UpdateMemberLevel(personMember))
            {
                QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."),
                                     tr("\n更新会员等级失败!"));
            }
            else
            {
                displayMemberLevel();
                emit updateMemberLevel();
            }
            break;
        }
    }
}

void SetMemberLevel::on_lineEditInitAmount_editingFinished()
{
    if (ui->lineEditInitAmount->text().toDouble() == 0)
    {
        ui->lineEditInitAmount->setText("0.00");
    }
    ui->lineEditInitAmount->setText(completionPrice(ui->lineEditInitAmount->text()));
}

void SetMemberLevel::on_lineEditMemberDiscount_editingFinished()
{
    if (ui->lineEditMemberDiscount->text().isEmpty()
            || ui->lineEditMemberDiscount->text().toInt() == 0)
    {
        ui->lineEditMemberDiscount->setText("100");
    }
}


void SetMemberLevel::on_lineEditInitIntegration_editingFinished()
{
    if (ui->lineEditInitIntegration->text().isEmpty()
            || ui->lineEditInitIntegration->text().toInt() == 0)
        ui->lineEditInitIntegration->setText("0");
}
